import akka.NotUsed
import akka.actor.typed.*
import akka.actor.typed.scaladsl.*
import akka.stream.*
import akka.stream.scaladsl.*

import java.nio.file.{Path, Paths}
import scala.concurrent.*
import scala.io.BufferedSource
import scala.util.*

@main def StreamTest: Unit = {
  val system = ActorSystem(Behaviors.empty, "test")
  given ex: ExecutionContext = system.executionContext
  given ma: Materializer = Materializer(system)

  val desc =
    """
    |abc
    |def

    |123
    |456

    |123
    |a1

    |b2
    |c3
      |""".stripMargin

  println("====================")
    val lines: Array[String] = desc.split("\n")
    val s: Source[String, NotUsed] = Source(lines)

  s.groupBy(2, line => line.contains("a"))
    .fold(Array[String]())( (list, line) => list.appended(line)) // lines to Array[String]
    .map( lines => lines.mkString(","))
    .mergeSubstreams
    .runForeach( s => println(s"get groupBy result: ${s}"))

  s.splitWhen( x => x.isEmpty) // split lines by empty line, empty line split to next stream head
    .filter( p=> !p.isEmpty) // drop empty lines
    .take(1)
    .fold(Array[String]())( (list, line) => list.appended(line)) // lines to Array[String]
    //.filter( lines => lines(0).contains("123")) // if 1 line of block is "123" , get it
    .map( lines => lines.mkString(","))
    .mergeSubstreams
    .map("get splitWhen result: " + _)
    .runForeach(println)
}

@main def StreamTest2 = {
  val system = ActorSystem(Behaviors.empty, "test")
  given ex: ExecutionContext = system.executionContext
  given ma: Materializer = Materializer(system)

  val s: BufferedSource = scala.io.Source.fromFile("/proc/bus/input/devices")
  val isLinked = s.getLines().filter(_.contains("Microsoft X-Box 360 pad")).size > 0
  println(isLinked)
}